package com.zwz.aop;

import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Invocation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

// 新增文件输出相关代码
public class MybatisInterceptor implements Interceptor {
    private static final Logger LOGGER = LoggerFactory.getLogger(MybatisInterceptor.class);
    // 新增：日志文件路径（src/main/resources/logs/sql.log）
    private static final String LOG_PATH = "src/main/resources/logs/sql.log";

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        long startTime = System.currentTimeMillis();
        Object returnValue = null;
        String sql = "";

        try {
            // 执行SQL并获取返回值
            returnValue = invocation.proceed();

            // 获取执行的SQL语句
            if (invocation.getTarget() instanceof StatementHandler) {
                StatementHandler statementHandler = (StatementHandler) invocation.getTarget();
                BoundSql boundSql = statementHandler.getBoundSql();
                sql = boundSql.getSql();
            }
        } finally {
            // 计算执行耗时
            long time = System.currentTimeMillis() - startTime;

            // 格式化日志内容（添加时间戳）
            String timestamp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(new Date());
            String logContent = String.format("[%s] SQL执行时间：%dms | SQL: %s",
                    timestamp, time, sql);

            // 写入日志文件
            writeLogToFile(logContent);

            // 控制台输出（可选）
            LOGGER.debug(logContent);
        }

        return returnValue;
    }



    // 新增：文件写入方法
    private boolean writeLogToFile(String content) {
        try {
            File logDir = new File("src/main/resources/logs");
            if (!logDir.exists()) logDir.mkdirs();

            FileWriter writer = new FileWriter(LOG_PATH, true);
            writer.write(content + "\n");
            writer.close();
            return true;
        } catch (IOException e) {
            LOGGER.error("日志文件写入失败: {}", e.getMessage());
            return  false;
        }
    }
}


